import logging
import os
import conf
from incl import *
from data_objects import *
from google.appengine.api import users
from google.appengine.ext import webapp
from google.appengine.ext.webapp import template
from google.appengine.ext.webapp.util import run_wsgi_app
from google.appengine.ext import db
from google.appengine.ext import blobstore
from google.appengine.ext.webapp import blobstore_handlers

class Recipes(db.Model):
  author = db.UserProperty(required=True)
  name = db.StringProperty(required=True)
  pub_date = db.DateTimeProperty(auto_now_add=True)
  descript = db.StringProperty(multiline=True)

class MainPage(webapp.RequestHandler):
  def get(self):
    recipes_query = Recipes.all().order('-pub_date');
    recipes = recipes_query.fetch(10)

    if users.get_current_user():
      url = users.create_logout_url(self.request.uri)
      url_linktext = 'Logout'
      self.redirect('/fe/')
    else:
      url = users.create_login_url(self.request.uri)
      url_linktext = 'Login'
      upload_url = ''

    template_values = {
      'recipes': recipes,
      'usernickname': users.get_current_user(),
      'is_user_admin': users.is_current_user_admin(),
      'url': url,
      'url_linktext': url_linktext,
      'config': conf,
      }

    path = os.path.join(os.path.dirname(__file__), 'index.html')
    self.response.out.write(template.render(path, template_values))

class RecipeBook(blobstore_handlers.BlobstoreUploadHandler):
  def post(self):
    
    recipe = Recipes(author=users.get_current_user(), 
                     name = "nobody")
    
    if users.get_current_user():
      recipe.author = users.get_current_user()
    
    recipe.name = self.request.get('name')
    recipe.descript = self.request.get('descript')
    recipe.put()
    
    self.redirect('/')

def main():
  application = webapp.WSGIApplication(
    [('/', MainPage),
     ('/post', RecipeBook),
    ], debug=True)
  run_wsgi_app(application)

if __name__ == "__main__":
  main()
